export default class SocketService {
  static instance = null
  static getInstance() {
    if (!this.instance) {
      this.instance = new SocketService()
    }
    return this.instance
  }

  ws = null
  callBackMapping = {}
  connected = false
  sendRetryCount = 0
  connectRetryCount = 0
  connect() {
    if (!window.WebSocket) {
      console.error('您的浏览器不支持WebSocket')
      return false
    }
    let url = 'ws://localhost:3001'
    this.ws = new WebSocket(url, 'echo-protocol')
    this.ws.onopen = () => {
      console.info('连接服务端成功了')
      this.connected = true
      this.connectRetryCount = 0
    }
    this.ws.onclose = () => {
      console.info('连接服务端失败')
      this.connected = false
      this.connectRetryCount++
      setTimeout(() => {
        this.connect()
      }, 500* this.connectRetryCount)
    }
    // 接收服务端发过来的数据
    this.ws.onmessage = msg => {
      console.info(msg.data)
    }
  }
  // 注册回调函数
  registerCallBack(type, callback) {
    this.callBackMapping[type] = callback
  }
  // 移去回调函数
  remvoeCallBack(type) {
    this.callBackMapping[type] = null
  }
  // 发送数据
  sendData(data) {
    if (this.connected) {
      this.sendRetryCount = 0
      try {
        this.ws.send(JSON.stringify(data))
      } catch (e) {
        this.ws.send(data)
      }
    } else {
      // 重新连接
    }
  }
}